package com.listener.service;

import com.listener.model.Customer;
import com.utils.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import java.util.List;

public class BusinessService {

    private HibernateUtil hibernateUtil = new HibernateUtil();
    private SessionFactory sessionFactory = hibernateUtil.getSessionFactory();

    private void loadCustomer() {
        Transaction tx = null;
        Session session = null;
        try {
//            session = sessionFactory.openSession();
//            tx = session.beginTransaction();
//            Customer customer = new Customer("周氏二爷");
//            session.save(customer);
//            tx.commit();
//
//            session = sessionFactory.openSession();
//            tx = session.beginTransaction();
//            customer.setName("qwe");
//            session.update(customer);
//            tx.commit();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();

            String sql = "SELECT c.id id ,c.name name FROM Customers c";
            List list = session.createSQLQuery(sql).addEntity(Customer.class).list();
            for (Object o : list) {
                Customer customer = (Customer) o;
                System.out.println(customer.toString());
            }
            tx.commit();
        } catch (RuntimeException e) {
            if (tx != null) {
                tx.rollback();
            }
            throw e;
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    private void test() {
        loadCustomer();
        sessionFactory.close();
    }

    public static void main(String args[]) {
        new BusinessService().test();
    }
}
